'use strict';
const fs = require('fs');
const { Sequelize, DataTypes,Op } = require('sequelize');
const { db_dialect, db_host, db_database, db_username, db_password } = require('../config/db');

// Option 3: Passing parameters separately (other dialects)
const sequelize = new Sequelize(db_database, db_username, db_password, {
    host: db_host,
    dialect: db_dialect
});

let files = fs.readdirSync(__dirname);

let resFiles = files.filter(item => {
    return item.endsWith('.js') && item !== 'index.js';
})

let resObj = {};
resFiles.forEach(item => {
    let modelName = item.replace('.js', '');
    let tmpObj = require(__dirname + '/' + item);
    // 这里我们需要的是这个模型的名称为modelName表示的值，而不是modelName这个变量本身被赋值为这个模型
    let tableName = modelName.toLowerCase();
    resObj[modelName] = sequelize.define(tableName, tmpObj);
})

// 逻辑运算包装
resObj.Op=Op

// 将模型同步的数据库，这里重新封装为一个异步函数，如果需要，才会被调用
resObj.sync = async () => {
    sequelize.sync({ force: true }).then(() => {
        resObj.Users.bulkCreate([
            {
                username: 'admin',
                password: '113',
                nickname: '超级管理员',
                avatar: '无'
            },
            {
                username: 'uu001',
                password: '113',
                nickname: '普通用户01',
                avatar: '无'
            },
            {
                username: 'uu002',
                password: '113',
                nickname: '普通用户02',
                avatar: '无'
            },
            {
                username: 'uu003',
                password: '113',
                nickname: '李雪琴',
                avatar: '无'
            },
        ]);

        resObj.Products.bulkCreate([
            {
                name:'女儿国的温柔',
                price:58,
                stock:100,
                supplier:'女儿国'
            },
            {
                name:'泰国金枕榴莲',
                price:68,
                stock:100,
                supplier:'百分号'
            },
            {
                name:'泰国的温柔',
                price:28,
                stock:1000,
                supplier:'泰国'
            },
            {
                name:'闽大的温柔',
                price:588,
                stock:100,
                supplier:'闽大'
            },
        ])
    });
}

module.exports = resObj;